<template>
	<div v-loading="loading">
		<el-dialog :title="mode == 'add' ? '新增会员日' : '编辑会员日'" :visible.sync="dialogVisible" fullscreen :close-on-click-modal="false" center @close="close">
			<div class="content">
				<el-form ref="form" :model="form" :rules="rules" label-width="150px" label-suffix="：" size="small">
					<el-form-item label="会员日" style="margin-bottom:0" class="is-required">
						<el-form-item style="display:inline-block" prop="right.dateType" :rules="rules.dateType">
							<el-select v-model="form.right.dateType" placeholder="请选择">
								<el-option v-for="item in dateTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
						<el-form-item v-if="form.right.dateType == 1" style="display:inline-block" prop="right.date" :rules="rules.date">
							<el-select v-model="form.right.date" placeholder="请选择"><el-option v-for="item in 31" :key="item" :label="item + '号'" :value="item" /></el-select>
						</el-form-item>
						<el-form-item v-if="form.right.dateType == 2" style="display:inline-block" prop="right.date" :rules="rules.date">
							<el-select v-model="form.right.date" placeholder="请选择">
								<el-option v-for="item in weekOptions" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-form-item>

					<el-form-item label="会员日折扣" prop="right.discount" :rules="rules.discount">
						<el-switch v-model="form.right.discount" active-color="#13ce66" inactive-color="#ff4949" />
						<el-collapse-transition>
							<div v-if="form.right.discount">
								<el-form-item v-for="(item, index) in form.categories" :key="item.categoryId" :prop="'categories.' + index" :rules="rules.discountAmount">
									<el-checkbox v-model="item.discountChecked">{{ item.categoryName }}{{ item.status ? '' : '(已停用)' }}</el-checkbox>
									&nbsp;&nbsp;
									<el-input v-model="item.discountAmount" placeholder="请输入" :disabled="!item.discountChecked" max="3" class="discount-input">
										<template slot="append">
											折
										</template>
									</el-input>
								</el-form-item>
							</div>
						</el-collapse-transition>
					</el-form-item>
					<el-form-item label="会员日积分" prop="right.point" :rules="rules.point">
						<el-switch v-model="form.right.point" active-color="#13ce66" inactive-color="#ff4949" />
						<el-collapse-transition>
							<div v-if="form.right.point">
								<el-form-item v-for="(item, index) in form.categories" :key="item.categoryId" :prop="'categories.' + index" :rules="rules.pointTimes">
									<el-checkbox v-model="item.pointChecked">{{ item.categoryName }}{{ item.status ? '' : '(已停用)' }}</el-checkbox>
									&nbsp;&nbsp;
									<el-input v-model="item.pointTimes" placeholder="请输入" :disabled="!item.pointChecked" max="3" class="discount-input">
										<template slot="append">
											倍
										</template>
									</el-input>
								</el-form-item>
							</div>
						</el-collapse-transition>
					</el-form-item>
					<el-form-item label="参与门店" prop="right.shop" :rules="rules.shop">
						<el-radio v-model="form.shopRadio_extra" :label="1">全部门店</el-radio>
						<br />

						<el-radio v-model="form.shopRadio_extra" :label="2" style="margin-right:10px">指定门店使用</el-radio>
						<el-button :disabled="form.shopRadio_extra !== 2" @click="openShopTree(form.right.shop)">
							已选择&nbsp;
							<span style="color:red">{{ form.right.shop.length }}</span>
							&nbsp;家门店
						</el-button>
					</el-form-item>
					<el-form-item v-if="superData.status == 1" label="超级会员" prop="right.superShop" :rules="rules.superShop">
						<p>注：开启后合作商户参与了活动，用户在会员日消费时候按照设置折扣优惠；</p>
						<p>积分奖励不需要合作商户参与，只要生成会员日就自动生效；</p>
						<p>此活动将默认按照与合作商户关系展示出资方；</p>
						<el-switch v-model="form.right.superSwitch" @change="superSwitchChange" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
						<div v-if="form.right.superSwitch">
							<el-radio v-model="form.superShopRadio_extra" :label="1" @change="superRadio">全部合作商户</el-radio>
							<br />
							<el-radio v-model="form.superShopRadio_extra" :label="2" style="margin-right:10px">部分合作商户</el-radio>
							<el-button :disabled="form.superShopRadio_extra !== 2" @click="openSuperShopTree()">
								已选择&nbsp;
								<span style="color:red">{{ form.right.superShopNum == 'all' ? 0 : form.right.superShop.length }}</span>
								&nbsp;家商户
							</el-button>
						</div>
					</el-form-item>
					<el-form-item label="详情介绍">
						<el-input
							v-model="form.right.detail"
							type="textarea"
							:autosize="{ minRows: 2, maxRows: 15 }"
							placeholder="请输入内容"
							maxlength="500"
							class="des-input"
							show-word-limit
						/>
						<div class="tips-info">详情介绍信息会在小程序展示给顾客</div>
					</el-form-item>
				</el-form>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" round @click="hide">取 消</el-button>
				<el-button size="small" round type="primary" @click="submit">确 定</el-button>
			</div>
		</el-dialog>

		<!-- 选择可用门店弹框 -->
		<DialogShopListTree ref="dialogShopListTree" title="可用门店" @emitShopIds="emitShopIds" />
		<DialogSuperShopListTree ref="dialogSuperShopListTree" title="选择合作商户" @emitSuperShopIds="emitSuperShopIds" />
	</div>
</template>

<script>
import { saveMemberDayConfig, judgeDiscountChange } from '@/api/marketing';
import { validateDis, validateMultiple } from '@/utils/validate.js';
export default {
	data() {
		/**
		 * 表单校验方法相关
		 */
		// 启用折扣
		const validateDiscount = (rule, value, callback) => {
			if (value) {
				let flag = false;
				this.form.categories.some(v => {
					if (v.discountChecked) {
						flag = true;
						return true;
					}
				});
				flag ? callback() : callback('启用会员日折扣请至少设置一个折扣权益');
				if (!this.form.right.point) {
					this.$refs.form.clearValidate(['right.point']);
				}
			} else if (!this.form.right.point) {
				callback('至少启用一种权益奖励');
			} else {
				callback();
			}
		};

		// 折扣
		const validateDiscountAmount = (rule, value, callback) => {
			if (value.discountChecked) {
				this.$refs.form.clearValidate(['right.discount']);
				if (value.discountAmount == '') {
					callback(new Error('请输入折扣'));
				} else if (!validateDis(value.discountAmount)) {
					callback(new Error('请输入正整数（不大于10），或正小数（小数位不超过1位）'));
				} else {
					callback();
				}
			} else {
				callback();
			}
		};

		// 启用积分
		const validatePoint = (rule, value, callback) => {
			if (value) {
				let flag = false;
				this.form.categories.some(v => {
					if (v.pointChecked) {
						flag = true;
						return true;
					}
				});
				flag ? callback() : callback('启用会员日积分请至少设置一个积分权益');
				if (!this.form.right.discount) {
					this.$refs.form.clearValidate(['right.discount']);
				}
			} else if (!this.form.right.discount) {
				callback('至少启用一种权益奖励');
			} else {
				callback();
			}
		};

		// 积分系数
		const validatePointTimes = (rule, value, callback) => {
			if (value.pointChecked) {
				this.$refs.form.clearValidate(['right.point']);
				if (value.pointTimes == '') {
					callback(new Error('请输入积分倍数'));
				} else if (!validateMultiple(value.pointTimes)) {
					callback(new Error('请输入1.1~9.9的倍数'));
				} else {
					callback();
				}
			} else {
				callback();
			}
		};

		//  可使用门店
		const validateShop = (rule, value, callback) => {
			if (this.form.shopRadio_extra === 2 && value.length === 0) {
				callback(new Error('请至少设置一家可使用门店'));
			} else {
				callback();
			}
		};

		//  可使用门店
		const validateSuperShop = (rule, value, callback) => {
			if (this.form.superShopRadio_extra === 2 && value.length === 0) {
				callback(new Error('请至少设置一家可使用商户'));
			} else {
				callback();
			}
		};
		return {
			/**
			 * 表单校验字段相关
			 */
			rules: {
				dateType: [
					{
						required: true,
						message: '请选择会员日类型',
						trigger: ['blur', 'change']
					}
				],
				date: [
					{
						required: true,
						message: '请选择会员日日期',
						trigger: ['blur', 'change']
					}
				],
				discount: [
					{
						required: true,
						validator: validateDiscount,
						trigger: ['blur', 'change']
					}
				],
				discountAmount: [
					{
						required: true,
						validator: validateDiscountAmount,
						trigger: ['blur', 'change']
					}
				],
				point: [
					{
						required: true,
						validator: validatePoint,
						trigger: ['blur', 'change']
					}
				],
				pointTimes: [
					{
						required: true,
						validator: validatePointTimes,
						trigger: ['blur', 'change']
					}
				],
				shop: [
					{
						type: 'array',
						required: true,
						validator: validateShop,
						trigger: ['blur', 'change']
					}
				],
				superShop: [
					{
						type: 'array',
						required: true,
						validator: validateSuperShop,
						trigger: ['blur', 'change']
					}
				]
			},
			// 配置
			mode: 'add',
			resolve: null,
			reject: null,
			dialogVisible: null,
			dateTypeOptions: [
				{
					value: 1,
					label: '每月'
				},
				{
					value: 2,
					label: '每周'
				}
			],
			weekOptions: [
				{
					value: 2,
					label: '周一'
				},
				{
					value: 3,
					label: '周二'
				},
				{
					value: 4,
					label: '周三'
				},
				{
					value: 5,
					label: '周四'
				},
				{
					value: 6,
					label: '周五'
				},
				{
					value: 7,
					label: '周六'
				},
				{
					value: 1,
					label: '周日'
				}
			],
			//  状态组
			loading: false,
			// 数据
			cardList: [],
			form: {
				right: {
					dateType: 1,
					date: 1,
					discount: true,
					point: true,
					shop: '',
					superSwitch: false,
					old_superSwitch: '',
					superShop: '',
					superShopNum: '',
					old_superShop: '',
					detail: '',
					mbDayId: null
				},
				categories: [],
				shopRadio_extra: 1,
				superShopRadio_extra: 1,
				openShopTreeType: null
			},
			// 超级会员
			superData: '' // status: 0:未开通 1:已开通 2:欠费停用
		};
	},
	watch: {
		'form.right.dateType'(val) {
			if (val === 1) {
				this.form.right.date = 1;
			} else {
				this.form.right.date = 2;
			}
		},
		form: {
			handler: function(val) {
				this.$nextTick(() => {
					// 门店
					if (val.shopRadio_extra === 1) {
						this.$refs.form.clearValidate(['right.shop']);
					} else if (val.shopRadio_extra === 2 && val.right.shop.length !== 0) {
						this.$refs.form.clearValidate(['right.shop']);
					}
				});
			},
			deep: true
		}
	},
	methods: {
		open({ mode, row = '', cardList = [], superData }) {
			this.mode = mode;
			this.cardList = cardList;
			this.superData = superData;
			this.fetchData(mode === 'add' ? this.form : row);
			this.show();
			return new Promise((resolve, reject) => {
				this.resolve = resolve;
				this.reject = reject;
			});
		},

		show() {
			this.dialogVisible = true;
		},

		close() {
			this.form = {
				right: {
					dateType: 1,
					date: 1,
					discount: true,
					point: true,
					shop: '',
					superShop: '',
					detail: ''
				},
				categories: [],
				shopRadio_extra: 1,
				superShopRadio_extra: 1
			};
			this.$refs.form.clearValidate();
			this.loading = false;
		},

		hide() {
			this.resolve = null;
			this.reject = null;
			this.dialogVisible = false;
		},
		/**
		 * 获取数据
		 */
		// 加载页面
		fetchData(row) {
			let that = this;
			this.loading = true;
			const data = JSON.parse(JSON.stringify(row));
			console.log('初始数据', data);
			// 生成卡数据格式
			const categoriesArr = [];
			this.cardList.map(val => {
				const obj = {};
				obj.categoryId = val.id;
				obj.categoryName = val.categoryName;
				obj.status = val.status;
				obj.discountChecked = false;
				obj.pointChecked = false;
				obj.discountAmount = '';
				obj.pointTimes = '';
				data.categories.map(v => {
					if (obj.categoryId === v.categoryId) {
						obj.discountChecked = !!v.discountAmount;
						obj.pointChecked = !!v.pointTimes;
						obj.discountAmount = v.discountAmount ? v.discountAmount / 10 : '';
						obj.pointTimes = v.pointTimes ? v.pointTimes / 10 : '';
					}
				});
				categoriesArr.push(obj);
			});

			if (data.right.shop) {
				data.right.shop = data.right.shop.split(',');
				data.shopRadio_extra = 2;
			} else {
				data.right.shop = [];
				data.shopRadio_extra = 1;
			}

			if (data.right.superMemberJoinBusinessIds) {
				data.right.superShop = data.right.superMemberJoinBusinessIds.split(',');
				data.superShopRadio_extra = 2;
			} else {
				data.right.superShop = [];
				data.superShopRadio_extra = 1;
			}
			data.right.mbDayId = data.right.id;
			data.right.superSwitch = data.right.openSuperMember;
			data.categories = categoriesArr;

			this.form = data;

			this.form.right.old_discount = data.right.discount;
			this.form.right.old_superSwitch = data.right.superSwitch;
			this.form.right.old_superShop = data.right.superShop.sort().toString();
			this.loading = false;

			// 解决会员日（周几）赋值问题
			let week = that.form.right.date;
			setTimeout(function() {
				that.form.right.date = week;
			}, 200);
		},

		/**
		 * 按钮组
		 */
		// 打开选择门店
		openShopTree() {
			this.form.right.shopTreeType = 'openShopTree';
			this.$refs.dialogShopListTree.open(this.form.right.shop);
		},
		// 选择可用门店
		emitShopIds(ids) {
			this.form.right.shop = ids;
			this.$refs.dialogShopListTree.hide();
		},
		// 超级会员-打开选择门店
		openSuperShopTree() {
			this.form.right.shopTreeType = 'openSuperShopTree';
			this.$refs.dialogSuperShopListTree.open(this.form.right.superShop, this.form.right.mbDayId, this.form.right.shopTreeType);
		},
		// 选择可用超级会员门店
		emitSuperShopIds(prams) {
			this.form.right.superShop = prams.checkedIds;
			this.$refs.dialogSuperShopListTree.hide();
			this.form.right.superShopNum = '';
			if (prams.shopNum == 'all') {
				this.form.right.superShopNum = 'all';
				this.form.superShopRadio_extra = 1;
			}
			this.form = Object.assign({}, this.form);
		},
		superSwitchChange(e) {
			this.form.superShopRadio_extra = 1;
			this.form.right.superShop = [];
		},
		superRadio(e) {
			this.form.right.superShop = [];
		},

		// 保存
		submit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					// 过滤数据
					const data = JSON.parse(JSON.stringify(this.form));
					// 门店
					if (data.shopRadio_extra === 1) {
						data.right.shop = '';
					} else {
						data.right.shop = data.right.shop.join(',');
					}
					delete data['shopRadio_extra'];
					// 卡信息
					for (let i = 0; i < data.categories.length; i++) {
						if (!data.categories[i].discountChecked && !data.categories[i].pointChecked) {
							data.categories.splice(i, 1);
							i--;
						} else {
							if (!data.right.discount || !data.categories[i].discountChecked) {
								data.categories[i].discountAmount = '';
							} else {
								data.categories[i].discountAmount = this.$math.mul(data.categories[i].discountAmount, 10, 0);
							}
							if (!data.right.point || !data.categories[i].pointChecked) {
								data.categories[i].pointTimes = '';
							} else {
								data.categories[i].pointTimes = this.$math.mul(data.categories[i].pointTimes, 10, 0);
							}
							delete data.categories[i]['discountChecked'];
							delete data.categories[i]['pointChecked'];
							delete data.categories[i]['categoryName'];
							delete data.categories[i]['status'];
						}
					}
					if (data.right.id) data.id = data.right.id;
					data.dateType = data.right.dateType;
					data.date = data.right.date;
					data.discount = data.right.discount;
					data.point = data.right.point;
					data.shop = data.right.shop;
					data.joinBusinessIds = data.right.superShop;
					data.openSuperMember = this.form.right.superSwitch;
					data.superMemberAllJoin = this.form.right.superSwitch && this.form.superShopRadio_extra == 1 ? true : false;
					data.detail = data.right.detail;
					delete data.right;
					console.log('保存', data);
					this.loading = true;

					// 判断修改弹窗内容
					this.judgeDialogFun(data);
				}
			});
		},

		judgeDialogFun(data) {
			let status = this.superData.status; // 1 已开通超级会员
			let changeType = '';

			let old_discount = this.form.right.old_discount; //旧开启状态
			let cur_discount = false;

			let old_superSwitch = this.form.right.old_superSwitch; //旧开启状态
			let superSwitch = this.form.right.superSwitch; //新开启状态
			let cur_superSwitch = false;

			let old_superShop = this.form.right.old_superShop; //旧商户
			let joinBusinessIds = data.joinBusinessIds.sort().toString(); //新商户
			let cur_superShop = false;

			if (status == 1 && this.mode != 'add') {
				judgeDiscountChange(data).then(res => {
					cur_discount = res.data;

					if (old_superSwitch) {
						if (old_superSwitch != superSwitch) {
							cur_superSwitch = true;
						}
						if (old_superShop != joinBusinessIds) {
							cur_superShop = true;
						}

						// console.log('cur_discount--', cur_discount);
						// console.log('cur_superSwitch--', cur_superSwitch);
						// console.log('cur_superShop--', cur_superShop);
						if ((!cur_discount && cur_superSwitch) || (!cur_discount && cur_superShop)) {
							changeType = 'superShop';
							this.changeConfirm(changeType, data);
						} else if (old_discount && cur_discount && !cur_superSwitch && !cur_superShop) {
							changeType = 'discount';
							this.changeConfirm(changeType, data);
						} else if ((old_discount && cur_discount && cur_superSwitch) || (old_discount && cur_discount && cur_superShop)) {
							changeType = 'discount';
							this.changeConfirm(changeType, data);
						} else {
							this.saveMemberDayConfigFun(data);
						}
					} else {
						this.saveMemberDayConfigFun(data);
					}
				});
			} else {
				this.saveMemberDayConfigFun(data);
			}
		},
		// 修改弹窗
		changeConfirm(changeType, data) {
			let txt = '';
			if (changeType == 'discount') {
				txt = '因会员日折扣有修改，保存后已参与活动的合作商家将重新操作参与，是否保存？';
			} else if (changeType == 'superShop') {
				txt = '因修改了参与的合作商户，会导致已参与活动的合作商户自动取消参与，请谨慎操作。';
			}
			this.$confirm(txt, '提示', {
				confirmButtonText: '继续保存',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.saveMemberDayConfigFun(data);
				})
				.catch(() => {
					this.loading = false;
					return;
				});
		},
		//保存配置
		saveMemberDayConfigFun(data) {
			saveMemberDayConfig(data)
				.then(res => {
					if (res.data == null) {
						this.$message({
							message: res.msg,
							type: 'warning'
						});
					} else {
						this.$notify({
							title: '成功',
							message: '保存成功',
							type: 'success',
							duration: 2000,
							offset: 40
						});
						this.resolve && this.resolve();
						this.hide();
					}
				})
				.catch(err => {})
				.finally(() => {
					this.loading = false;
				});
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.content {
	margin: 0 auto;
	width: 60%;
	min-width: 800px;
	max-width: 900px;
}

/* 输入框 */
.discount-input {
	width: 160px;
}
.des-input {
	width: 600px;
}
::v-deep .el-textarea .el-input__count {
	line-height: 1;
}

/* 提示 */
.tips-info {
	line-height: 1.5;
	font-size: 12px;
	color: #909399;
}
</style>
